#include "uartx.h"

Uartx_t *u1;
Uartx_t *u2;
Uartx_t *u3;

Uartx_t* uartx_structInit(const uint8_t *header, const uint8_t *tail)
{
    Uartx_t *u = (Uartx_t*)malloc(sizeof(Uartx_t));
    if(u == NULL) return NULL;
    
    memcpy(u->Header, header, 2);
    memcpy(u->Tail, tail, 2);
    u->Index = 0;
    u->Start = 0;
    u->Cplt = 0;
    memset(u->RxBuffer, 0, RX_LEN);  // 清空缓冲区
    return u;
}

void uartx_process(Uartx_t *u)
{
    uint8_t receivedChar = u->RxChar;
    
    if (!u->Start)
    {
        if (receivedChar == u->Header[0] && u->Index == 0)
        {
            u->RxBuffer[u->Index++] = receivedChar;
        }
        else if (receivedChar == u->Header[1] && u->Index == 1)
        {
            u->RxBuffer[u->Index++] = receivedChar;
            u->Start = 1;  
        }
        else u->Index = 0; 
    }
    else 
    {
        if (u->Index >= RX_LEN)
        {
            u->Index = 0;
            u->Start = 0;
            u->Cplt = 0;
            return;
        }
        u->RxBuffer[u->Index++] = receivedChar;
        if (u->Index >= 4)
        {
            if (u->RxBuffer[u->Index-2] == u->Tail[0] && u->RxBuffer[u->Index-1] == u->Tail[1])
            {
                u->RxBuffer[u->Index] = '\0';
                u->Cplt = 1;
                u->Start = 0;
                // 在这里可以调用处理完整帧的函数
                // processCompleteFrame(u);
//                printf("%s\r\n", u->RxBuffer);

                u->Index = 0;
            }
        }
    }
}
uint8_t uartx_TaskNumber(Uartx_t *u){
	if (!u->Cplt) return 0;
	uint8_t ch = u->RxBuffer[2];
	if (ch >= '1' && ch <= '6')
			return ch - '0';   
	else
			return 0;          
}

/* 解码，把串口接收到的41位hex解码成float */
float uartx_DecodeFloat(const uint8_t* bytes) 
{
    union {
        float float_value;
        uint8_t bytes[4];
    } converter;
    for(int i = 0; i < 4; i++) {
        converter.bytes[i] = bytes[i];
    }
    return converter.float_value;
}
uint16_t SringToUint16(uint8_t ch[])
{
	uint16_t temp = 0;
	for(int i = 1000, j = 0; j < 4; i /= 10, j++)
	{
		temp += (ch[j] - '0') * i;
	}
	return temp;
}
/* CRC-16 IMB 校验 */
uint16_t uartx_Crc16(const uint8_t *data, size_t length) 
{
    uint16_t crc = 0xFFFF;
    for (size_t i = 0; i < length; ++i) {
        crc ^= data[i];
        for (int j = 0; j < 8; ++j) {
            if (crc & 0x0001) {
                crc >>= 1;
                crc ^= 0xA001;
            } else {
                crc >>= 1;
            }
        }
    }
    return crc; // 返回 CRC16 校验值（网络传输通常用大端）
}

/* printf 重定向 */
int fputc(int ch, FILE * f){
	HAL_UART_Transmit(&huart3, (uint8_t *)&ch, 1, 0xffff);
  while(__HAL_UART_GET_FLAG(&huart3, UART_FLAG_TC) == RESET);
  return ch;
}
